import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "@/app/store";

interface UserState {
	name: string;
	token: string;
}

interface UserFormData {
	username: string;
	password: string;
}

function getInitialState(): UserState {
	const localUser = localStorage.getItem("user");
	if (localUser) {
		return JSON.parse(localUser);
	} else {
		return {
			name: "",
			token: "",
		};
	}
}

// 初始化状态
let initialState: UserState = getInitialState();

// 异步action
export const loginAsync = createAsyncThunk(
	"user/login",
	(user: UserFormData): Promise<UserState> => {
		// 模拟异步请求
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				if (user.username === "shangguigu" && user.password === "111111") {
					resolve({
						name: "admin",
						token: "admin_token",
					});
				} else {
					reject("用户名或密码错误");
				}
			}, 1000);
		});
	}
);

// 创建redux模块
export const userSlice = createSlice({
	name: "user",
	// 初始化状态数据
	initialState,
	// reducer函数 --> 会自动生成同步action函数
	// 语法：const { login } = userSlice.actions;
	reducers: {
		// login: (state, action: PayloadAction<UserState>) => {
		// 	state.name = action.payload.name;
		// 	state.token = action.payload.token;
		// },
	},
	// reducer函数 --> 专门处理异步action函数
	extraReducers: (builder) => {
		builder
			// 代表异步action执行中
			// .addCase(loginAsync.pending, (state) => {
			// 	state.status = "loading";
			// })
			// 代表异步action执行成功
			.addCase(loginAsync.fulfilled, (state, action) => {
				// 将数据存储到redux中
				state.name = action.payload.name;
				state.token = action.payload.token;
				// 将数据持久化存储
				localStorage.setItem("user", JSON.stringify(action.payload));
			});
		// .addCase(loginAsync.rejected, (state, action) => {
		// 	state.error = action.error.message;
		// });
	},
});

// 用来获取数据
export const selectUser = (state: RootState) => state.user;

export default userSlice.reducer;
